//
//  ZLNotification.m
//  ZLNotification
//
//  Created by 科大物联 on 2023/7/7.
//

#import "ZLNotification.h"
@class ZLNotification;

@interface KDCWNotificationItemModel : NSObject
@property (nonatomic, copy) NSString *target;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) ZLNotificationItemComplete complete;
@end

@implementation KDCWNotificationItemModel

- (instancetype)initWithTarget:(NSString *)target name:(NSString *)name object:(id)object complete:(ZLNotificationItemComplete)complete {
    if (self = [super init]) {
        self.target = target;
        self.name = name;
        self.complete = complete;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:name object:object];
    }
    return self;
}

- (void)notificationAction:(NSNotification *)notification {
    if (self.complete) {
        self.complete(notification);
    }
}

@end

@interface ZLNotification()
@property (nonatomic, strong) NSMutableArray *notifArray;
@end

@implementation ZLNotification

+ (instancetype)shared {
    static ZLNotification *_shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shared = [[ZLNotification alloc] init];
    });
    return _shared;
}

+ (void)postNotification:(NSString *)name object:(id)object {
    [[NSNotificationCenter defaultCenter] postNotificationName:name object:object];
}

+ (void)addNotification:(NSString *)target name:(NSString *)name complete:(ZLNotificationItemComplete)complete {
    [self addNotification:target name:name object:nil complete:complete];
}

+ (void)addNotification:(NSString *)target name:(NSString *)name object:(id)object complete:(ZLNotificationItemComplete)complete {
    KDCWNotificationItemModel *item = [[KDCWNotificationItemModel alloc] initWithTarget:target name:name object:object complete:complete];
    [[self shared].notifArray addObject:item];
}

+ (void)removeNotification:(NSString *)target {
    [self removeNotification:target name:@""];
}

+ (void)removeNotification:(NSString *)target name:(NSString *)name {
    NSArray *notifArray = [[self shared].notifArray copy];
    [notifArray enumerateObjectsUsingBlock:^(KDCWNotificationItemModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if (name.length == 0) {
            if ([model.target isEqualToString:target]) {
                [[self shared].notifArray removeObject:model];
            }
        } else {
            if ([model.target isEqualToString:target] && model.name == name) {
                [[self shared].notifArray removeObject:model];
            }
        }
    }];
}

+ (void)removeAllNotification {
    [[self shared].notifArray removeAllObjects];
}

- (NSMutableArray *)notifArray {
    if (!_notifArray) {
        _notifArray = [NSMutableArray array];
    }
    return _notifArray;
}

@end
